package com.cwj.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cwj.blog.common.R;
import com.cwj.blog.entity.Blog;
import com.cwj.blog.service.BlogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private BlogService blogService;

    /**
     * 新增博客
     */
    @PostMapping
    public R<String> save(@RequestBody Blog blog) {
        if (!"".equals(blog.getTitle().trim())) {
            blogService.save(blog);
            return R.success(null, "添加成功");
        } else {
            return R.error("标题和内容不能为空");
        }
    }

    /**
     * 修改博客
     */
    @PutMapping
    public R<String> update(@RequestBody Blog blog) {
        blogService.updateById(blog);
        return R.success(null, "修改成功");
    }

    /**
     * 查询所有数据
     */
    @GetMapping("/list")
    public R<List<Blog>> list(String title) {
        //构造条件构造器
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        //添加筛选条件
        queryWrapper.like(StringUtils.isNotEmpty(title), Blog::getTitle, title);
        //添加排序条件
        queryWrapper.orderByDesc(Blog::getCreateTime);
        List<Blog> list = blogService.list(queryWrapper);
        return R.success(list, list.size(), "查询成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<List<Blog>> page(long skip, int pageSize, String title) {
        //构造分页构造器
        Page<Blog> pageInfo = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        //添加筛选条件
        queryWrapper.like(StringUtils.isNotEmpty(title), Blog::getTitle, title);
        //添加排序条件
        queryWrapper.orderByDesc(Blog::getCreateTime);
        //执行查询
        blogService.page(pageInfo, queryWrapper);

        List<Blog> records = pageInfo.getRecords().stream()
                .skip((skip - 1) * pageSize).limit(pageSize).collect(Collectors.toList());

        return R.success(records, blogService.list().size(), "查询成功");
    }

    /**
     * 删除数据
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        blogService.removeByIds(ids);
        return R.success(null, "删除成功");
    }

    /**
     * 通过id查询
     */
    @GetMapping("/{id}")
    public R<Blog> get(@PathVariable Long id) {
        Blog blog = blogService.getById(id);
        if (blog != null) {
            return R.success(blog, "查询成功");
        } else {
            return R.error("没有找到该数据", 0);
        }
    }
}
